const { prisma } = require('../config/prisma');

/**
 * 群组成员模型 - Prisma版本
 */
class GroupMemberPrisma {
  constructor(data) {
    this.id = data.id;
    this.group_id = data.group_id;
    this.user_id = data.user_id;
    this.role = data.role;
    this.joined_at = data.joined_at;
    
    // 关联数据
    this.users = data.users;
    this.chat_groups = data.chat_groups;
  }

  /**
   * 添加成员到群组
   * @param {Object} memberData 成员数据
   * @returns {Promise<GroupMemberPrisma>}
   */
  static async create(memberData) {
    const { group_id, user_id, role = 'member' } = memberData;

    // 检查是否已经是成员
    const existing = await this.findByGroupAndUser(group_id, user_id);
    if (existing) {
      throw new Error('用户已经是群组成员');
    }

    const member = await prisma.group_members.create({
      data: {
        group_id: parseInt(group_id),
        user_id: BigInt(user_id),
        role
      }
    });

    return new GroupMemberPrisma(member);
  }

  /**
   * 根据群组和用户查找成员关系
   * @param {number} groupId 群组ID
   * @param {number} userId 用户ID
   * @returns {Promise<GroupMemberPrisma|null>}
   */
  static async findByGroupAndUser(groupId, userId) {
    const member = await prisma.group_members.findFirst({
      where: {
        group_id: parseInt(groupId),
        user_id: BigInt(userId)
      }
    });

    return member ? new GroupMemberPrisma(member) : null;
  }

  /**
   * 获取群组成员列表
   * @param {number} groupId 群组ID
   * @param {Object} options 查询选项
   * @returns {Promise<Object>}
   */
  static async getGroupMembers(groupId, options = {}) {
    const { page = 1, pageSize = 50 } = options;
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const skip = (pageNum - 1) * pageSizeNum;

    const where = { group_id: parseInt(groupId) };

    // 并行查询总数和列表数据
    const [total, members] = await Promise.all([
      prisma.group_members.count({ where }),
      prisma.group_members.findMany({
        where,
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
              phone_number: true
            }
          }
        },
        orderBy: { joined_at: 'desc' },
        skip,
        take: pageSizeNum
      })
    ]);

    const membersWithUserInfo = members.map(member => ({
      id: member.id.toString(),
      group_id: member.group_id.toString(),
      user_id: member.user_id.toString(),
      role: member.role,
      joined_at: member.joined_at,
      user: {
        nickname: member.users?.nickname,
        avatar_url: member.users?.avatar_url,
        phone_number: member.users?.phone_number
      }
    }));

    return {
      data: membersWithUserInfo,
      pagination: {
        page: pageNum,
        pageSize: pageSizeNum,
        total,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    };
  }

  /**
   * 获取用户的群组列表
   * @param {number} userId 用户ID
   * @returns {Promise<Array>}
   */
  static async getUserGroups(userId) {
    const members = await prisma.group_members.findMany({
      where: { user_id: BigInt(userId) },
      include: {
        chat_groups: {
          select: {
            id: true,
            group_name: true,
            group_avatar: true,
            description: true
          }
        }
      },
      orderBy: { joined_at: 'desc' }
    });

    return members.map(member => ({
      id: member.id.toString(),
      group_id: member.group_id.toString(),
      user_id: member.user_id.toString(),
      role: member.role,
      joined_at: member.joined_at,
      group: {
        group_name: member.chat_groups?.group_name,
        group_avatar: member.chat_groups?.group_avatar,
        description: member.chat_groups?.description
      }
    }));
  }

  /**
   * 更新成员角色
   * @param {number} groupId 群组ID
   * @param {number} userId 用户ID
   * @param {string} role 新角色
   * @returns {Promise<GroupMemberPrisma|null>}
   */
  static async updateRole(groupId, userId, role) {
    try {
      const member = await prisma.group_members.update({
        where: {
          group_id_user_id: {
            group_id: parseInt(groupId),
            user_id: BigInt(userId)
          }
        },
        data: { role }
      });

      return new GroupMemberPrisma(member);
    } catch (error) {
      if (error.code === 'P2025') { // Record not found
        return null;
      }
      throw error;
    }
  }

  /**
   * 移除群组成员
   * @param {number} groupId 群组ID
   * @param {number} userId 用户ID
   * @returns {Promise<boolean>}
   */
  static async remove(groupId, userId) {
    try {
      await prisma.group_members.delete({
        where: {
          group_id_user_id: {
            group_id: parseInt(groupId),
            user_id: BigInt(userId)
          }
        }
      });
      return true;
    } catch (error) {
      if (error.code === 'P2025') { // Record not found
        return false;
      }
      throw error;
    }
  }

  /**
   * 检查用户是否是群组成员
   * @param {number} groupId 群组ID
   * @param {number} userId 用户ID
   * @returns {Promise<boolean>}
   */
  static async isMember(groupId, userId) {
    const member = await this.findByGroupAndUser(groupId, userId);
    return !!member;
  }

  /**
   * 检查用户是否是群组管理员或群主
   * @param {number} groupId 群组ID
   * @param {number} userId 用户ID
   * @returns {Promise<boolean>}
   */
  static async isAdmin(groupId, userId) {
    const member = await this.findByGroupAndUser(groupId, userId);
    return member && ['admin', 'owner'].includes(member.role);
  }

  /**
   * 获取群组成员统计
   * @param {number} groupId 群组ID
   * @returns {Promise<Object>}
   */
  static async getGroupMemberStats(groupId) {
    const groupIdInt = parseInt(groupId);

    const [total, owners, admins, members] = await Promise.all([
      prisma.group_members.count({ where: { group_id: groupIdInt } }),
      prisma.group_members.count({ where: { group_id: groupIdInt, role: 'owner' } }),
      prisma.group_members.count({ where: { group_id: groupIdInt, role: 'admin' } }),
      prisma.group_members.count({ where: { group_id: groupIdInt, role: 'member' } })
    ]);

    return { total, owners, admins, members };
  }

  /**
   * 获取所有群组的成员列表（去重，全国总群用）
   * @param {Object} options 查询选项
   * @returns {Promise<Object>}
   */
  static async getAllGroupsMembers(options = {}) {
    const { page = 1, pageSize = 50 } = options;
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const skip = (pageNum - 1) * pageSizeNum;

    // 获取所有群聊类型群组的成员，按用户去重
    const members = await prisma.group_members.findMany({
      where: {
        chat_groups: {
          group_type: 'group' // 只获取群聊成员，排除私聊
        }
      },
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true
          }
        }
      },
      orderBy: { joined_at: 'desc' }
    });

    // 按用户ID去重
    const uniqueMembers = [];
    const seenUserIds = new Set();

    for (const member of members) {
      const userId = member.user_id.toString();
      if (!seenUserIds.has(userId)) {
        seenUserIds.add(userId);
        uniqueMembers.push(member);
      }
    }

    // 分页处理
    const total = uniqueMembers.length;
    const paginatedMembers = uniqueMembers.slice(skip, skip + pageSizeNum);

    const membersWithUserInfo = paginatedMembers.map(member => ({
      id: member.id.toString(),
      group_id: member.group_id.toString(),
      user_id: member.user_id.toString(),
      role: member.role,
      joined_at: member.joined_at,
      user: {
        nickname: member.users?.nickname,
        avatar_url: member.users?.avatar_url
      }
    }));

    return {
      data: membersWithUserInfo,
      pagination: {
        page: pageNum,
        pageSize: pageSizeNum,
        total,
        totalPages: Math.ceil(total / pageSizeNum),
        hasMore: skip + pageSizeNum < total
      }
    };
  }

  /**
   * 批量添加成员
   * @param {number} groupId 群组ID
   * @param {Array<number>} userIds 用户ID数组
   * @param {string} role 角色
   * @returns {Promise<Array<GroupMemberPrisma>>}
   */
  static async batchAdd(groupId, userIds, role = 'member') {
    // 检查哪些用户已经是成员
    const existingMembers = await prisma.group_members.findMany({
      where: {
        group_id: parseInt(groupId),
        user_id: { in: userIds.map(id => BigInt(id)) }
      },
      select: { user_id: true }
    });

    const existingUserIds = existingMembers.map(m => m.user_id.toString());
    const newUserIds = userIds.filter(id => !existingUserIds.includes(id.toString()));

    if (newUserIds.length === 0) {
      return [];
    }

    // 批量创建新成员
    const createData = newUserIds.map(userId => ({
      group_id: parseInt(groupId),
      user_id: BigInt(userId),
      role
    }));

    await prisma.group_members.createMany({
      data: createData
    });

    // 返回新创建的成员
    const newMembers = await prisma.group_members.findMany({
      where: {
        group_id: parseInt(groupId),
        user_id: { in: newUserIds.map(id => BigInt(id)) }
      }
    });

    return newMembers.map(member => new GroupMemberPrisma(member));
  }

  /**
   * 转换为JSON对象
   * @returns {Object}
   */
  toJSON() {
    return {
      id: this.id.toString(),
      group_id: this.group_id.toString(),
      user_id: this.user_id.toString(),
      role: this.role,
      joined_at: this.joined_at
    };
  }
}

module.exports = GroupMemberPrisma;
